;
(function (window, angular) {
    'use strict';
    angular.module("Service.UserContext", [])
        .constant("UserType", {"Common": 1, "Sale": 2, 'Payment': 3, 'Market': 4, 'Operator': 101})
        .constant("REPORT_TYPE", {SALE: 0, PURCHASE: 1})
        .service("UserContextService", ["$http", "$q", "UserType", "ybHttp", "ybConfig", "$window", "$filter", "EventBus", "REPORT_TYPE", "SecurityUtil", "Upload", "securityRetryQueue", "$rootScope", "ybWidget", "MESG_TYPE",
            function ($http, $q, UserType, ybHttp, ybConfig, $window, $filter, EventBus, REPORT_TYPE, SecurityUtil, Upload, queue, $rootScope, ybWidget, MESG_TYPE) {
                var _platform = window.AppData.platform;
                var _primaryMenu = [];
                var _secondaryMenu = [];
                var _rights;

                var fnPlatform = function () {
                    return _platform;
                };

                var fnPrimaryMenu = function () {
                    return _primaryMenu;
                };

                var fnSecondaryMenu = function (menu) {
                    return _secondaryMenu[menu];
                };

                var ApplyRights = function () {
                    //todo 根据登录用户获取权限
                    var service = "auth";
                    var reqUrl = "/scepter/getAuthCodes";
                    ybHttp.Get(service, reqUrl).then(function (resp) {
                        if (resp.code !== 0) {
                            return;
                        }
                        _rights = resp.value;
                        window.sessionStorage.setItem("AuthCodes", _rights);
                    });
                };

                function fnGetAuthCodes(){
                    _rights = window.sessionStorage.getItem("AuthCodes");
                    if(!!_rights){
                        _rights = _rights.split(",");
                        for (var i = 0; i < _rights.length;i++){
                            _rights[i] = parseInt(_rights[i]);
                        }
                        return;
                    }
                    ApplyRights();
                }


                function fnCheckPermission(ids) {
                    var ret = false;
                    if (!ids || ids.length == 0 || angular.isUndefined(_rights)) {
                        return true;
                    }
                    for (var i = 0; i < ids.length; ++i) {
                        ret = $filter('contains')(_rights, ids[i]);
                        if (ret) {
                            return ret;
                        }
                    }
                    return ret;
                }

                var fnLogin = function (user) {
                    var deferred = $q.defer();
                    var service = "auth";
                    var reqUrl = "/auth/login";
                    const userData = angular.copy(user);
                    userData.version = '20220805'
                    // userData.password = window.btoa(window.btoa(user.password))
                    var result = ybHttp.Post(service, reqUrl, userData);
                    result.then(function (data) {
                            if (data.code === 0) {
                                localStorage.setItem("ScAuthM", data.value.ScAuth);
                                deferred.resolve(data.value);
                                return;
                            }
                            deferred.reject(data.message);
                        },
                        function (data) {
                            deferred.reject(data.message);
                        });
                    return deferred.promise;
                };

                // onlyClearCach 退出只清除保存的缓存信息（不传参，默认清除+调用退出接口）
                var fnLogOut = function (onlyClearCach) {
                    _rights = undefined;
                    window.sessionStorage.removeItem("menu");
                    window.sessionStorage.removeItem("AuthCodes");
                    window.sessionStorage.removeItem("UserInfo");
                    window.sessionStorage.removeItem("CompanyInfo");
                    if (!onlyClearCach) {
                        ybHttp.Post('auth', '/auth/logout');
                        $window.location.href = ybConfig.getConfig().baseUrl.LoginSite;
                    }
                };

                function _getUserInfo() {
                    var service = "auth";
                    var reqUrl = "/profile/getLogin";
                    ybHttp.Get(service, reqUrl).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        EventBus.Publish("getUserInfo", resp.value);
                    });
                }


                //js浮点型数字运算addition:加法，subtraction：减法，multiply：乘法,division:除法
                function fnAccNumber(type, arg1, arg2) {
                    var r1, r2, m, t1, t2, result;
                    if (arg1.toString().split('.').length > 1) {
                        r1 = arg1.toString().split('.')[1].length
                    } else {
                        r1 = 0
                    }
                    if (arg2.toString().split('.').length > 1) {
                        r2 = arg2.toString().split('.')[1].length
                    } else {
                        r2 = 0;
                    }
                    t1 = Number(arg1.toString().replace('.', ''));
                    t2 = Number(arg2.toString().replace('.', ''));
                    switch (type) {
                        case 'addition':
                            result = (t1 * Math.pow(10, r2) + t2 * Math.pow(10, r1)) / Math.pow(10, r1 + r2);
                            break;
                        case 'subtraction':
                            result = (t1 * Math.pow(10, r2) - t2 * Math.pow(10, r1)) / Math.pow(10, r1 + r2);
                            break;
                        case 'multiply':
                            m = Math.pow(10, r1 + r2);
                            result = t1 * t2 / m;
                            break;
                        case 'division':
                            m = Math.pow(10, r2 - r1);
                            result = (t1 / t2) / m;
                            break;
                        default:
                            break;
                    }
                    return result;
                }

                var fnSetSubMenu = function (menuItem, jumpToFirst) {
                    var menuItem = {
                        jumpToFirst: jumpToFirst,
                        menuItem: menuItem
                    };
                    EventBus.Publish("setSubMenu", menuItem);
                };

                var fnSetUserAuth = function (menuItem, jumpToFirst) {
                    var menuItem = {
                        jumpToFirst: jumpToFirst,
                        menuItem: menuItem
                    };
                    EventBus.Publish("setSubMenu", menuItem);
                };

                var fnGetUserAuth = function (menuItem, jumpToFirst) {
                    var menuItem = {
                        jumpToFirst: jumpToFirst,
                        menuItem: menuItem
                    };
                    EventBus.Publish("setSubMenu", menuItem);
                };

                var fnFindNodeInTree = function (srcRoot, nodeId) {
                    var result = {};
                    var found = false;

                    function traverse(root) {
                        if (found || !root) {
                            return;
                        }
                        var id = root.id || root.Code;
                        if (id == nodeId) {
                            result = root;
                            found = true;
                            return;
                        }
                        if (!root.children) {
                            return;
                        }
                        for (var i = 0; i < root.children.length; i++) {
                            if (found) {
                                return;
                            }
                            traverse(root.children[i]);
                        }
                    }

                    traverse(srcRoot);
                    return result;
                };

                var fnUpdateCheckedTreeNode = function (root, node) {
                    var nodeParentId = node.parentId || node.ParentCode;
                    if (!!node.children && (node.isChecked != "notAll")) {
                        setChildrenState(node.children, node.isChecked);
                    }
                    setParentState(nodeParentId, node.isChecked);
                    function setChildrenState(list, state) {
                        angular.forEach(list, function (item) {
                            item.isChecked = state;
                            if (!!item.children) {
                                setChildrenState(item.children, item.isChecked);
                            }
                        })
                    }

                    function setParentState(parentId, state) {
                        if (!parentId) {
                            return;
                        }
                        var parent = fnFindNodeInTree(root, parentId);
                        var grandpaId = parent.parentId || parent.ParentCode;
                        if (parent.isChecked == "notAll") {
                            if (state == "notAll") {
                                return;
                            }
                            var checkedNum = getCheckedNum();
                            if (state == true && (checkedNum == parent.children.length)) {
                                parent.isChecked = true;
                                setParentState(grandpaId, true);
                            }
                            if (state == false && (checkedNum == 0)) {
                                parent.isChecked = false;
                                setParentState(grandpaId, false);
                            }
                            return;
                        }

                        if (parent.isChecked == true) {
                            var num = getCheckedNum();
                            if ((state == "notAll") || ((state == false) && ( num > 0))) {
                                parent.isChecked = "notAll";
                                setParentState(grandpaId, "notAll");
                            }
                            if ((state == false) && ( num == 0)) {
                                parent.isChecked = false;
                                setParentState(grandpaId, false);
                            }
                            return;
                        }
                        if (parent.isChecked == false) {
                            var num = getCheckedNum();
                            if ((state == "notAll") || ((state == true) && ( num < parent.children.length ))) {
                                parent.isChecked = "notAll";
                                setParentState(grandpaId, "notAll");
                            }
                            if ((state == true) && ( num == parent.children.length )) {
                                parent.isChecked = true;
                                setParentState(grandpaId, true);
                            }
                            return;
                        }

                        function getCheckedNum() {
                            var num = 0;
                            angular.forEach(parent.children, function (item) {
                                if (item.isChecked == true) {
                                    num++;
                                }
                            });
                            return num;
                        }
                    }
                };
                var fnUpdateTreeNode = function (root, node) {//选中子类不会影响父类状态，但不选子类也会取消父类选中状态
                    var nodeParentId = node.parentId || node.ParentCode;
                    if (!!node.children && (node.isChecked != "notAll")) {
                        setChildrenState(node.children, node.isChecked);
                    }
                    setParentState(nodeParentId, node.isChecked);
                    //父类选中时，子类都会被选中
                    function setChildrenState(list, state) {
                        angular.forEach(list, function (item) {
                            item.isChecked = state;
                            if (!!item.children) {
                                setChildrenState(item.children, item.isChecked);
                            }
                        })
                    }

                    //子类未选中时，父类也取消选中
                    function setParentState(parentId, state) {
                        if (!parentId) {
                            return;
                        }
                        var parent = fnFindNodeInTree(root, parentId);
                        var grandpaId = parent.parentId || parent.ParentCode;
                        if (parent.isChecked == true) {
                            var num = getCheckedNum();
                            if ((state == false) && ( num == 0)) {
                                parent.isChecked = false;
                                setParentState(grandpaId, false);
                            }
                            return;
                        }
                        function getCheckedNum() {
                            var num = 0;
                            angular.forEach(parent.Children, function (item) {
                                if (item.isChecked == true) {
                                    num++;
                                }
                            });
                            return num;
                        }
                    }
                };

                var fnDebounce = function(fn, delay) {
                    var timer;
                    return function() {
                        if (timer) clearTimeout(timer);
                        timer = setTimeout(function() {
                            fn();
                        }, delay);
                    }
                };
                return {
                    Platform: fnPlatform,
                    PrimaryMenu: fnPrimaryMenu,
                    SecondaryMenu: fnSecondaryMenu,
                    Login: fnLogin,
                    Logout: fnLogOut,
                    CheckPermission: fnCheckPermission,
                    GetUserInfo: _getUserInfo,
                    AccNumber: fnAccNumber,
                    SetSubMenu: fnSetSubMenu,
                    SetUserAuth: fnSetUserAuth,
                    GetUserAuth: fnGetUserAuth,
                    UpdateCheckedTreeNode: fnUpdateCheckedTreeNode,
                    FindNodeFormTree: fnFindNodeInTree,
                    UpdateTreeNode: fnUpdateTreeNode,
                    Debounce:fnDebounce,
                    GetAuthCodes: fnGetAuthCodes
                }
            }
        ])
        .service("MenuLogService", ["$interval", "ybHttp", "UserContextService", function ($interval, ybHttp, UserContextService) {
            var countList = [];

            function _countCode(topCode, menuCode) {
                var cell = {
                    TopCode: -1,
                    MenuCode: 0,
                    Count: 0
                };
                var length = countList.length;
                var isNew = true;
                cell.MenuCode = menuCode;
                cell.TopCode = topCode;
                if (cell.TopCode == -1) {
                    return;
                }
                for (var i = 0; i < length; i++) {
                    if (countList[i].TopCode == cell.TopCode && countList[i].MenuCode == cell.MenuCode) {
                        countList[i].Count++;
                        isNew = false;
                        break;
                    }
                }
                if (isNew) {
                    cell.Count = 1;
                    countList.push(cell);
                }
            }

            function _updateCounterToServer() {
                if (!countList || !countList.length) {
                    return;
                }
                var param = {};
                param.counterList = angular.toJson(countList);
                ybHttp.Post("HumanBehavior/UpdateMenuCounter", param).then(function (data) {
                    if (data.Code != 0) {
                        //do nothing
                        return;
                    }
                    countList = [];
                });

            }

            function _pushResult() {
                $interval(_updateCounterToServer, 180000);
            }

            return {
                CountCode: _countCode,
                PushResult: _pushResult
            };
        }])
    ;
})
(window, window.angular);
